// pages/viewHistory/viewHistories.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEmpty:false,
    pagination: 1, // 页码
    histories: [],
    startX: 0, //开始坐标
    startY: 0,
    nomore: false,
    isEnd: false
  },

  toSimilar(e){
    const that = this;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/search/search?id=${id}&where=similar`,
    })
  },

  // 跳转详情
  toDetail(e){
    const that = this;
    let id = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${id}`
    })
  },

  /**
   * 手指触摸动作开始 记录起点X坐标
  */
  touchstart: function (e) {
    console.log(e)
    //开始触摸时 重置所有删除
    this.data.histories.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      histories: this.data.histories
    })
  },
  /**
   * 滑动事件处理
  */
  touchmove: function (e) {
    console.log(e)
    var that = this,
      key = e.currentTarget.dataset.key,//当前父级索引
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });

    this.data.histories.forEach(function (v, k) {
      v.visit.forEach(function (item, i) {
        item.isTouchMove = false
        //滑动超过30度角 return
        if (Math.abs(angle) > 30) return;
        if (key == k && index == i) {
          if (touchMoveX > startX) //右滑
            item.isTouchMove = false
          else //左滑
            item.isTouchMove = true
        }
      })
    })

    //更新数据
    that.setData({
      histories: that.data.histories
    })
  },
  /**
   * 计算滑动角度
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  getList() {
    const that = this;
    let json = {
      token: app.globalData.token,
      p: that.data.pagination
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.historylist, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      console.log(res)
      let arr = [];
      if (res.status == 1) {
        if(res.result.length == 0){
          that.setData({
            isEmpty: true
          })
        } else {
          res.result.forEach(item => {  //  获取缩略图
            app.getImg(item.visit);
          })
          that.setData({
            histories: res.result
          })
        }
      } else {
        throw res.msg;
      }
    }).catch(err => {
      app.showInfo(err.toString())
    })
  },

  getMoreList() {
    const that = this;
    if (that.data.isEnd) {
      return
    }
    let json = {
      token: app.globalData.token,
      p: that.data.pagination + 1
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.historylist, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      console.log(res)
      let arr = [];
      if (res.status == 1) {
        if (res.result.length == 0) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
          that.setData({
            isEnd: true
          })
        } else {
          res.result.forEach(item => {  //  获取缩略图
            app.getImg(item.visit);
          })
          that.setData({
            histories: [...that.data.histories, ...res.result],
            pagination: that.data.pagination + 1
          })
        }
      } else {
        throw res.msg;
      }
    }).catch(err => {
      app.showInfo(err.toString())
    })
  },

  delHistory(e){
    const that = this;
    let key = e.currentTarget.dataset.key;
    let index = e.currentTarget.dataset.index;
    console.log(key, index)
    let json = {
      visit_ids: e.currentTarget.dataset.visitid,
      token: app.globalData.token
    }
    let jsonData = app.utils.getSignData(json);
    wx.showModal({
      title: '',
      content: '是否删除该浏览记录',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          app.utils.post(app.api.reqUrls.del_history, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            if (res.status == 1) {
              that.data.histories[key].visit.splice(index, 1);
              that.setData({
                histories: that.data.histories
              })
            } else {
              throw res.msg;
            }
          }).catch(err => {
            app.showInfo(err.toString())
          })
        } else {
          console.log('取消删除')
        }
      }
    })

  },

  clear() {
    const that = this;
    let json = {
      token: app.globalData.token
    }
    let jsonData = app.utils.getSignData(json);
    wx.showModal({
      title: '',
      content: '是否清空浏览记录',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          app.utils.post(app.api.reqUrls.clear_history, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            if (res.status == 1) {
              that.setData({
                isEmpty: true,
                histories: []
              })
              wx.showToast({
                title: res.msg,
                icon: "success",
                duration: 1000
              })
              app.getInfo(app.globalData.token)
            } else {
              throw res.msg;
            }
          }).catch(err => {
            app.showInfo(err.toString())
          })
        } else {
          console.log('取消删除')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.getList();
  },
  onShow:function(){
    //数据统计
    app.statistics("page/detail/pages/viewHistories/viewHistories", "浏览记录")
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const that = this;
    that.getMoreList();
  }
})